#include "clkCamera.h"

clkCamera::clkCamera()
{
	m_camX      = 0;
	m_camY      = 0;
	m_camZ      = 0;
	m_camXMin   = 0;
	m_camXMax   = 0;
	m_camYMin   = 0;
	m_camYMax   = 0;
	m_camZMin   = 0;
	m_camZMax   = 0;
	m_camSpd    = 0;
	m_camZoom   = 0;
	m_camAttPos = 0;

	m_mouseMove   = true;
	m_mouseScrl = true;
}

clkCamera::~clkCamera()
{

}

void clkCamera::initCamera(
	V3DF  a_pos,
	float a_yaw,
	float a_pitch,
	float a_aspect,
	float a_near,
	float a_far,
	float a_fov,
	float a_xMin,
	float a_xMax,
	float a_yMin,
	float a_yMax,
	float a_zMin,
	float a_zMax,
	float a_dis,
	float a_spd,
	float a_zoom,
	bool  a_move,
	bool  a_scrl)
{
	m_cam.m_pos    = a_pos;
	m_cam.m_yaw    = RADIAN(a_yaw);
	m_cam.m_pitch  = RADIAN(a_pitch);
	m_cam.m_aspect = a_aspect;
	m_cam.m_near   = a_near;
	m_cam.m_far    = a_far;
	m_cam.m_fov    = a_fov;
	m_cam.m_dis    = a_dis;

	m_camXMin = a_xMin;
	m_camXMax = a_xMax;
	m_camYMin = a_yMin;
	m_camYMax = a_yMax;
	m_camZMin = a_zMin;
	m_camZMax = a_zMax;
	m_camSpd  = a_spd;
	m_camZoom = a_zoom;

	m_mouseMove = a_move;
	m_mouseScrl = a_scrl;
}

void clkCamera::input()
{
	m_din->mouseDelta(&m_camX,&m_camY,&m_camZ);
}

void clkCamera::update()
{
	if(m_mouseMove)
	{
		m_cam.m_yaw   += m_camX * m_camSpd;
		m_cam.m_pitch += m_camY * m_camSpd;

		if(m_camXMin == m_camXMax)
		{
			if(m_cam.m_yaw < 0.0f)
				m_cam.m_yaw += D3DXToRadian(360.0f);
			else if(m_cam.m_yaw > D3DXToRadian(360.0f))
				m_cam.m_yaw -= D3DXToRadian(360.0f);
		}
		else
		{
			if(m_cam.m_yaw < D3DXToRadian(m_camXMin))
				m_cam.m_yaw = D3DXToRadian(m_camXMin);
			else if(m_cam.m_yaw > D3DXToRadian(m_camXMax))
				m_cam.m_yaw  = D3DXToRadian(m_camXMax);
		}

		if(m_camYMin == m_camYMax)
		{
			if(m_cam.m_pitch < 0.0f)
				m_cam.m_pitch += D3DXToRadian(360.0f);
			else if(m_cam.m_pitch > D3DXToRadian(360.0f))
				m_cam.m_pitch -= D3DXToRadian(360.0f);
		}
		else
		{
			if(m_cam.m_pitch < D3DXToRadian(m_camYMin))
				m_cam.m_pitch = D3DXToRadian(m_camYMin);
			else if(m_cam.m_pitch > D3DXToRadian(m_camYMax))
				m_cam.m_pitch  = D3DXToRadian(m_camYMax);
		}
	}

	if(m_mouseScrl)
	{
		m_cam.m_dis -= m_camZ * m_camZoom;

		if(m_camZMin != m_camZMax)
		{
			if(m_cam.m_dis < m_camZMin)
				m_cam.m_dis = m_camZMin;
			else if(m_cam.m_dis > m_camZMax)
				m_cam.m_dis = m_camZMax;
		}
	}

	if(m_camAttPos)
		m_cam.m_pos = *m_camAttPos + m_camAttOff;

	m_d3d->updateCamera(m_cam);
}

void clkCamera::attach(V3DF* a_pos, V3DF a_off)
{
	m_camAttPos = a_pos;
	m_camAttOff = a_off;
}